var happyReader = {
	curTabIdx:0,
	curPage:1,
	curSiteNextPageLevel:0,
	nextPageUrl:'',
	isRun:false,
	setUserConfig:function(key,value){
		localStorage[key] = value;
	},
	getUserConfig:function(key){
		return localStorage[key];
	},
	main:function(viewMode){
		var iframeUrl = this.getSpecialIFrameUrl();
		if (!options_enableAnalysisHelper) {
            happyReader.getData();
        }
		this.filterTag(document);
		this.getNextPageUrl();
		this.init();
		if (iframeUrl && iframeUrl[0]) {
            this.runConfigInit("text");
			this.getContentFromSpecialIFrame(iframeUrl);
        }else if (happyReaderMenu.selection){
			this.getContentFromSelection();
			this.runConfigInit("text");
		}else{
			this.runConfigInit(viewMode);
		}
		this.isRun = true;
	},
	//for some special site that content in iframe
	getSpecialIFrameUrl:function(){
		var url = location.href;
		if (url.indexOf("http://xue.youdao.com/")==0) {
			return $('#articleViewFrame').attr('src');
		}
	},
	filterTag:function(doc){
		var tags = ["meta", "link", "script", "style", "iframe", "object", "input", "select", "textarea"];
		tags.forEach(function(item){
			var items = doc.getElementsByTagName(item),ci;
			while (ci = items[0]){
				ci.parentNode.removeChild(ci);
			} 
		});
	},
	getData:function(){
		try{
            this.getImgData();
			happyReaderText.getData();
			happyReaderLink.getData(document);
		}
		catch(e){}
	},
	getImgData:function(){
		var contentDom = $.createEle("div").html($('body').html().replace(/<!--(.*?)-->/igm,""))[0];
	    this.filterTag(contentDom);
	    happyReaderImg.getData(contentDom);  //chrome 7 should use document instead of contentDom[0];
	    $.removeEle(contentDom);
		contentDom = null;
	},
	_downloadUrl:function(url){
		var ev = document.createEvent('MouseEvents');
        ev.initMouseEvent('click', false, false, window, 1, 0, 0, 0, 0, false, true, false, false, 0, null);
        $.createEle('a',{href:url})[0].dispatchEvent(ev);
	},
	init:function(){
		$.loadfile({
			'type':'css', 
			'url':chrome.extension.getURL('css/style.css')
		});
		var slideLock = false, 
            tabsIdx = [],
            html = 
			'<header id="happyReaderHeader">'
				+'<div id="happyReaderGoback">'+_m("goBack")+'</div>'
				+'<nav>$imgTab$textTab$linkTab</nav>'
				+'<div id="happyReaderHeaderAD"></div>'
			+'</header>'
			+'<section id="happyReaderBody">$imgCanvas$textCanvas$linkCanvas</section>'
		
		for(var idx in options_enableTabs) {
			var tabHtml = '', canvasHtml = '', lowerIdx = idx.toLowerCase();
			if (options_enableTabs[idx]) {
				tabHtml = '<li id="'+lowerIdx+'Tab">'+_m(lowerIdx)+'</li>';
				canvasHtml = '<div id="'+lowerIdx+'Canvas"></div>';
				tabsIdx.push(lowerIdx);
			}
			html = html.replace('$'+lowerIdx+'Tab', tabHtml).replace('$'+lowerIdx+'Canvas', canvasHtml);
		}
		try {
			$.removeEle($('body'));
			$('html').css({overflow:''});
		}catch(e){
			document.body.parentNode.removeChild(document.body);
		}
		
		$.createEle('body').html(html).appendTo($('html'));

		function tabSlide(selfID){
			if (slideLock)return;
			slideLock = true;
			
			var type = selfID.replace('Tab',''),
				newTabIdx = tabsIdx.indexOf(type),
				curTabIdx = happyReader.curTabIdx;
				
			if (newTabIdx == curTabIdx)return;
			window['happyReader'+type.replace(/\w/, function(s){return s.toUpperCase()})].init();
			
			$('#'+tabsIdx[curTabIdx]+'Tab').attr({className:'', onclick:function(){tabSlide(this.id)}});
			$('#'+type+'Tab').attr({className:'at', onclick:null});
			var curCanvas = $('#'+type+'Canvas').show(),
			    lastCanvas = $('#'+tabsIdx[curTabIdx]+'Canvas').css({opacity:0});
			
			setTimeout(function(){
				curCanvas.css({opacity:1, left: 0});
			},100);
			
			setTimeout(function(){
				lastCanvas.css({left:'-3000px'}).hide();
				happyReader.curTabIdx = newTabIdx;
				slideLock = false;
				_gaq.push(['_trackEvent', 'click::tabSlide_' + tabsIdx[newTabIdx], 'click']);
			}, 420);
			document.body.scrollTop = 0;
		}
		
		$('#happyReaderGoback').attr({
			onclick: function(){
				_gaq.push(['_trackEvent', 'goBack::curMode_' + happyReader.getUserConfig("viewMode"), 'goBack']);
				setTimeout(function(){location.reload()},100)
			}
		});
		tabsIdx.forEach(function(tabName){
			$('#'+tabName+'Tab').attr({onclick:function(){tabSlide(this.id);}});
		});
		$('#happyReaderHeaderAD').attr({onclick:function(){_gaq.push(['_trackEvent', 'click::headerAD', 'click']);}});
		
		setTimeout(function(){
		    $('#happyReaderHeader').show();
			setTimeout(function(){happyReader.showHeader();},50);
			document.onselectstart = null;
		},50);
	},
	runConfigInit:function(mode){
        var viewMode = this.getViewMode(mode);
		_gaq.push(['_trackEvent', 'init::viewMode_' + viewMode, 'init']);
		switch(viewMode){
			case "text":
				happyReaderText.init();
				$('#textTab').attr({className:'at'});
                happyReader.curTabIdx = 1;
				break;
			case "link":
			    happyReaderLink.init();
				$('#linkTab').attr({className:'at'});
				happyReader.curTabIdx = 2;
			    break;
			default:
				happyReaderImg.init();
				$('#imgTab').attr({className:'at'});
                happyReader.curTabIdx = 0;
		}
		document.body.scrollTop = 0;
	},
	showHeader:function(){
		$('#happyReaderHeader').css({top:0});
	},
	hideHeader:function(){
		var happyReaderHeader = $('#happyReaderHeader'),
            happyReaderHeaderTop = parseInt(happyReaderHeader.css('left')) || 0;
		
		happyReaderHeaderTop >= 0 && happyReaderHeader.css({top:'-100px'});
	},
	getViewMode:function(mode){
		return mode || 
		       (happyReaderImg.checkModeValid() ? 'img' : (happyReaderText.checkModeValid() ? 'text' : this.getUserConfig("viewMode"))) || 
			   'img';
	},
	getNextPageUrl:function(doc){
		function getPossibleNextPageUrls(){
            var uri = (doc||document).location.pathname, 
			    uriArr = uri.split('/'), 
				pageName = uriArr.pop().split('.'),
				extName = '.'+pageName.pop(),
			    curIdx = (function(idx){
					if(!idx)return [];
					
					var i=0, item, tmpIdx, s = ['-', '_'];
					for(;item=s[i++];){
						tmpIdx = idx.split(item);
						if (tmpIdx.length > 1) {
							return [tmpIdx.shift() + item + (parseInt(tmpIdx) + 1)];
						}
					}
					return [parseInt(idx)+1, idx+'-1', idx+'_1'];
				})(pageName.shift()),
			    nextUrlPre = location.origin+uriArr.join('/')+'/';
                nextUrls = [];
				
			curIdx.forEach(function(item){
				nextUrls.push(nextUrlPre+item+extName);
			});
			return nextUrls;
        }
		
		function setNextPageLevel(level, href){
			nextPage.level <= level && (nextPage = {url:href,level:level});
            happyReader.curSiteNextPageLevel = level;
		}
		
		this.curSiteNextPageLevel = 0;
		
		var href,
		    host = location.host,
		    nextPage = {url:'', level:0},
		    links = (doc || document).getElementsByTagName('a');
		for(var i=0,item;item=links[i++];){
			href = item.href;
			if (href && href.indexOf(location.origin)==0 && href.search(/#|#nogo|javascript|mailto/i) == -1 && item.innerHTML != null) {
                linkText = item.innerHTML.replace(/<.*?>/g,"").trim();
				if (this.curSiteNextPageLevel < 10 && linkText.indexOf('\u4e0b\u4e00\u9875')>=0 || linkText.indexOf('\u4e0b\u4e00\u7bc7')>=0 || linkText.indexOf('\u4e0b\u4e00\u7ae0')>=0 || linkText.indexOf('\u4e0b\u4e00\u8282')>=0 || linkText.indexOf('\u4e0b\u9875')>=0){
					setNextPageLevel(10, href);
	            }else if (this.curSiteNextPageLevel<7 && /pagenext/i.test(item.id)){
				   setNextPageLevel(7, href);
				}else if (this.curSiteNextPageLevel<5 && /next/i.test(linkText)){
				   setNextPageLevel(5, href);
	            }

				if (this.curSiteNextPageLevel < 10){
					if (getPossibleNextPageUrls().indexOf(href) > -1) {
						setNextPageLevel(10, href);
                    }	
				}
			}
		}
		this.nextPageUrl = nextPage.url;
	},
	getNextPageContent:function(){
        setTimeout(function(){
            $.createEle('div', {id:'textCanvas_loading'}).html('Loading .... ').appendTo($('#textCanvas'));
			var nextPageUrl = happyReader.nextPageUrl;
			if (nextPageUrl) {
				if (options_enableSuperAutoNextPage) {
					chrome.extension.connect({name:'nextPageConn'}).postMessage({action:'getNextPageContent',url:nextPageUrl});
					return ;
				}
				
				$.createEle('iframe', {
                    id:'happyReader_nextPage_'+(++happyReader.curPage),
                    src:nextPageUrl,
                    onload: function(){
                        happyReader.getNextPageUrl(this.contentDocument);
						
						var doc = this.contentDocument, 
						    nextContent = happyReaderText.getData(doc) || ('<article><p>'+_m('noText')+'</p></article>');

                        $.removeEle($('#textCanvas_loading'));
						$.createEle('article').css({background:happyReaderText.getTextSkinBg(),width:happyReaderText.getArticlePageWidth(happyReaderText.getTextPageWidth())}).html("<span class='hrRemove'><b>X</b></span><page>"+happyReader.curPage+"/<totalPage>1</totalPage></page><div class='happyReaderEditable' style='padding:0 8px;'>"+nextContent+"</div>").appendTo($('#textCanvas'));
						happyReaderText.updateFontSize(happyReaderText.getFontSize());
						
						var totalPages = document.getElementsByTagName('totalPage');
						for(var i=0, totalPage; totalPage=totalPages[i++];){
							totalPage.innerHTML = happyReader.curPage;
						};
						
						happyReader.getNextPageContent();
						$.removeEle($(this));
						document.querySelector('#textCanvas article').style.minHeight=0;
                    }
                },{display:'none',position:'absolute',left:'-1000px',top:'-1000px'}).appendTo($('body'));
            }else{
				$.removeEle($('#textCanvas_loading'));
			}
        }, 800);
	},
	getContentFromSpecialIFrame:function(url){
		this.curPage--;
		$('#textCanvas').html('<div id="textCanvas_loading" style="background:#fff;color:#000;">Loading .... </div>');
		chrome.extension.connect({name:'nextPageConn'}).postMessage({action:'getNextPageContent',url:url});
	},
	getContentFromSelection:function(){
		happyReaderText.title = document.title;
		happyReaderText.content = happyReaderMenu.selection;
		happyReaderText.textData = happyReaderText.getTextData(happyReaderText.title, happyReaderText.content);
	},
	copyToClipboard:function(text){
		chrome.extension.connect({name:'copyConn'}).postMessage({action:'copyToClipboard', value:text});
	}
};
